package org.example.crypto.util;

import org.example.crypto.bean.CryptoInfoBean;
import org.example.crypto.config.ApiCryptoProperties;
import org.example.crypto.enums.CryptoType;
import org.example.crypto.exception.EncryptMethodNotFoundException;
import org.example.crypto.exception.KeyNotConfiguredException;
import org.springframework.util.StringUtils;

/**
 * @program: rabbitmq-study
 * @description:
 * @Version V1.0.0
 * @author: dazhi
 * @create: 2021-02-09 14:21
 **/
public class ApiCryptoUtil {
    /***
     * 功能描述:选择加密方式并进行解密
     * @author: dazhi
     * @date: 2021/2/9
     */

    public static byte[] decryptData(ApiCryptoProperties properties, byte[] bodyData, CryptoInfoBean infoBean) {
        CryptoType cryptoType = infoBean.getCryptoType();
        if (cryptoType == null) {
            throw new EncryptMethodNotFoundException();
        }

        String secretKey = infoBean.getSecretKey();
        if (cryptoType == CryptoType.DES) {
            secretKey = ApiCryptoUtil.checkSecretKey(properties.getDesKey(), secretKey, "DES");
           // return DesUtil
        }
        throw new EncryptMethodNotFoundException();
    }

    private static String checkSecretKey(String desKey, String secretKey, String des) {
        if (StringUtils.isEmpty(desKey) && StringUtils.isEmpty(secretKey)) {
             throw  new KeyNotConfiguredException(String.format("%s key is not configured (未配置%s)", des, des));
        }
        return StringUtils.isEmpty(secretKey) ? desKey:secretKey;
    }
}
